package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * Author: Felix
 * Date: 2022/4/6
 * Desc: 业务数据动态分流
 */
public class TableProcessFunction extends BroadcastProcessFunction<JSONObject, String, JSONObject> {

    private OutputTag<JSONObject> dimTag;
    private MapStateDescriptor<String, TableProcess> mapStateDescriptor;
    private Connection conn;

    public TableProcessFunction(OutputTag<JSONObject> dimTag, MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.dimTag = dimTag;
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //注册驱动
        Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
        //建立连接
        conn = DriverManager.getConnection(GmallConfig.PHOENIX_URL);
    }

    //处理非广播流(业务流)数据
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        //获取操作的业务数据库表名
        String table = jsonObj.getString("table");
        //获取操作的类型
        String type = jsonObj.getString("type");
        //注意：如果使用maxwell的bootstrap同步历史数据，那么历史数据的type是bootstrap-insert ，我们这里统一修正为insert
        if (type.equals("bootstrap-insert")) {
            type = "insert";
            jsonObj.put("type", type);
        }
        //根据表名和操作类型拼接从广播状态中获取配置的key
        String key = table + ":" + type;

        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);

        //根据拼接的key，到广播状态中获取当前处理的业务流数据对应的配置信息
        TableProcess tableProcess = broadcastState.get(key);

        if (tableProcess != null) {
            //不管是事实还是维度，在向下游传递数据前，都需要补充输出的目的地
            String sinkTable = tableProcess.getSinkTable();
            jsonObj.put("sink_table", sinkTable);

            //在向下游传递数据前，需要对data中传输的内容进行过滤，有些属性不需要传递到下游的
            // data":{"tm_name":"wls","logo_url":"ccc","id":14}
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");
            // id,tm_name
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj,sinkColumns);

            //说明在配置表中找到了当前操作的数据对应配置信息，就可以判断当前处理的业务数据是维度还是事实了
            String sinkType = tableProcess.getSinkType();
            if (TableProcess.SINK_TYPE_HBASE.equals(sinkType)) {
                //维度数据-----放到维度侧输出流中
                ctx.output(dimTag, jsonObj);
            } else if (TableProcess.SINK_TYPE_KAFKA.equals(sinkType)) {
                //事实数据----放到主流中
                out.collect(jsonObj);
            }

        } else {
            //说明在配置表中没有找到当前操作的数据 对应配置信息  ,那么就没有办法进行分流，没有办法向下游传递，相当于将这个操作过滤掉了
            System.out.println("No this Key in TableProcess:" + key);
        }
    }



    //处理广播流数据
    //jsonStr  {"database":"gmall0925_realtime","table":"table_process","type":"insert","data":{"source_table":"","operator_type":""....}}
    @Override
    public void processBroadcastElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
        //为了处理方便，将json字符串转换为json对象
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        //获取配置表中一条配置信息
        JSONObject dataJsonObj = jsonObj.getJSONObject("data");
        //将读取到的一条配置信息封装为一个TableProcess对象
        TableProcess tableProcess = dataJsonObj.toJavaObject(TableProcess.class);

        //获取业务数据库表名
        String sourceTable = tableProcess.getSourceTable();
        //获取操作类型
        String operateType = tableProcess.getOperateType();
        //获取输出类型  hbase  kafka
        String sinkType = tableProcess.getSinkType();
        //获取输出目的地
        String sinkTable = tableProcess.getSinkTable();
        //保留的字段
        String sinkColumns = tableProcess.getSinkColumns();
        //获取建表主键
        String sinkPk = tableProcess.getSinkPk();
        //获取建表扩展
        String sinkExtend = tableProcess.getSinkExtend();
        //拼接放到广播状态中的key
        String key = sourceTable + ":" + operateType;

        //判断当前读取的是不是维度配置，如果是，提前创建维度表
        if (TableProcess.SINK_TYPE_HBASE.equals(sinkType) && "insert".equals(operateType)) {
            checkTable(sinkTable, sinkColumns, sinkPk, sinkExtend);
        }

        //获取广播状态
        BroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //将读取的一条配置信息放到广播状态中
        broadcastState.put(key, tableProcess);

    }

    //过滤不需要传递的属性
    // dataJsonObj":{"tm_name":"wls","logo_url":"ccc","id":14}
    // sinkColumns:id,tm_name
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        String[] columnArr = sinkColumns.split(",");
        List<String> columnList = Arrays.asList(columnArr);
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry->!columnList.contains(entry.getKey()));
    }

    //维度表的创建
    private void checkTable(String tableName, String fields, String pk, String ext) {
        if (pk == null) {
            pk = "id";
        }
        if (ext == null) {
            ext = "";
        }
        //拼接建表语句
        StringBuilder createSql = new StringBuilder("create table if not exists " + GmallConfig.PHOENIX_SCHEMA + "." + tableName + "(");

        //获取表中的所有字段
        String[] fieldArr = fields.split(",");
        for (int i = 0; i < fieldArr.length; i++) {
            String field = fieldArr[i];
            if (field.equals(pk)) {
                createSql.append(field + " varchar primary key");
            } else {
                createSql.append(field + " varchar ");
            }
            if (i < fieldArr.length - 1) {
                createSql.append(",");
            }
        }
        createSql.append(") " + ext);
        System.out.println("在phoenix中建表语句：" + createSql);

        PreparedStatement ps = null;
        try {
            //获取数据库操作对象
            ps = conn.prepareStatement(createSql.toString());
            //执行SQL语句
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
